<template>
	<a-form :ref="'ruleForm'" :model="formState" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
		<a-row :gutter="[10, 10]">
			<a-col :span="24" class="mb-2">
				<a-radio-group
					v-model:value="formState.dataSetConfig.dataSetType"
					optionType="button"
					buttonStyle="solid"
					:options="[
						{ label: '静态', value: 0 },
						{ label: '数据源', value: 1 }
					]"
				>
				</a-radio-group>
			</a-col>

			<template v-if="formState.dataSetConfig.dataSetType == 0">
				<a-col :span="24">
					<StaticDataTable v-model="formState.data.listValue.value" @update="updateData" />
				</a-col>
			</template>
			<template v-else>
				<a-col :span="24">
					<SelectTree @onChange="selectTreeChange" v-model:paramsJson="formState.dataSetConfig.dataSetJson" />
				</a-col>
				<a-col :span="24">
					<a-form-item label="标题" class="form-item">
						<a-select
							style="width: 100%"
							placeholder="请选择数据源"
							v-model:value="formState.data.title.field"
							optionLabelProp="label"
						>
							<a-select-option
								v-for="optionItem in dataOption"
								:value="optionItem"
								:key="optionItem"
								:label="optionItem"
							>
								{{ optionItem }}
							</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :span="24">
					<a-form-item label="链接" class="form-item">
						<a-select
							style="width: 100%"
							placeholder="请选择数据源"
							v-model:value="formState.data.link.field"
							optionLabelProp="label"
						>
							<a-select-option
								v-for="optionItem in dataOption"
								:value="optionItem"
								:key="optionItem"
								:label="optionItem"
							>
								{{ optionItem }}
							</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :span="24">
					<a-form-item label="数值" class="form-item">
						<a-select
							style="width: 100%"
							placeholder="请选择数据源"
							v-model:value="formState.data.numValue.field"
							optionLabelProp="label"
						>
							<a-select-option
								v-for="optionItem in dataOption"
								:value="optionItem"
								:key="optionItem"
								:label="optionItem"
							>
								{{ optionItem }}
							</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :span="24">
					<a-form-item label="图标key" class="form-item">
						<a-select
							style="width: 100%"
							placeholder="请选择数据源"
							v-model:value="formState.data.iconKey.field"
							optionLabelProp="label"
						>
							<a-select-option
								v-for="optionItem in dataOption"
								:value="optionItem"
								:key="optionItem"
								:label="optionItem"
							>
								{{ optionItem }}
							</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :span="24">
					<a-form-item label="图标颜色" class="form-item">
						<a-select
							style="width: 100%"
							placeholder="请选择数据源"
							v-model:value="formState.data.iconColor.field"
							optionLabelProp="label"
						>
							<a-select-option
								v-for="optionItem in dataOption"
								:value="optionItem"
								:key="optionItem"
								:label="optionItem"
							>
								{{ optionItem }}
							</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :span="24">
					<a-form-item label="背景颜色" class="form-item">
						<a-select
							style="width: 100%"
							placeholder="请选择数据源"
							v-model:value="formState.data.iconBgColor.field"
							optionLabelProp="label"
						>
							<a-select-option
								v-for="optionItem in dataOption"
								:value="optionItem"
								:key="optionItem"
								:label="optionItem"
							>
								{{ optionItem }}
							</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
			</template>
		</a-row>
	</a-form>
</template>

<script setup>
	import { defineEmits, defineProps, reactive, ref, watch } from 'vue'
	import StaticDataTable from './StaticDataTable.vue'
	import SelectTree from '@/views/plugin/dashboard/plugin/public/SelectTree/SelectTree.vue'
	import datasetApi from '@/views/plugin/dashboard/api/datasetApi'
	import { designStore } from '@/views/plugin/dashboard/store'
	// -----------------------------------------------------------
	import config from '../config'
	import { cloneDeep } from 'lodash-es'

	const useDesignStore = designStore()
	const emits = defineEmits(['upDataConfig'])
	const props = defineProps({
		config: {
			type: Object,
			default: () => {
				return cloneDeep(config)
			}
		}
	})

	// 创建本地配置缓存，用于存储用户修改但尚未确认的配置
	const localConfig = reactive(cloneDeep(props.config))

	// 使用标记位避免循环更新
	const isUpdatingFromProps = ref(false)

	// 表单状态使用本地配置
	const formState = reactive({
		data: localConfig.data,
		dataSetConfig: localConfig.dataSetConfig
	})

	// 更新数据
	const updateData = () => {
		// 触发数据更新
		setTimeout(() => {
			// 更新本地配置
			Object.assign(localConfig, {
				data: formState.data,
				dataSetConfig: formState.dataSetConfig
			})
			// 更新预览配置
			emits('upDataConfig', cloneDeep(localConfig))
		}, 100)
	}

	// 数据变化清空下拉
	const selectTreeChange = () => {
		formState.data.title.field = undefined
		formState.data.link.field = undefined
		formState.data.numValue.field = undefined
		formState.data.iconKey.field = undefined
		formState.data.iconColor.field = undefined
		formState.data.iconBgColor.field = undefined
	}

	// 数据源
	const dataSource = ref([])
	// 模拟接口返回下拉数据
	const dataOption = ref([])
	// 记录当前已加载的数据源ID，避免重复加载
	const loadedDataSourceId = ref('')
	// 获取下拉数据
	watch(
		() => formState.dataSetConfig.dataSetJson,
		(newVal) => {
			if (formState.dataSetConfig.dataSetType === 1 && newVal && newVal.id) {
				// 如果已经加载过这个数据源，则不重复加载
				if (loadedDataSourceId.value === newVal.id) {
					return
				}

				const list = useDesignStore.dataSource || []
				let datasetId = ''
				let indicatorId = ''
				list.forEach((parent) => {
					parent.config.indicators.forEach((child) => {
						if (child.id === newVal.id) {
							datasetId = parent.id
							indicatorId = child.id
						}
					})
				})
				if (datasetId && indicatorId) {
					// 记录当前加载的数据源ID
					loadedDataSourceId.value = newVal.id

					// 下拉数据
					datasetApi.querySelectedColumns({ datasetId, indicatorId }).then((res) => {
						dataOption.value = res || []
					})
					datasetApi.preview(newVal).then((res) => {
						dataSource.value = res || []
						formState.data.listValue.value = res || []
					})
				}
			}
		},
		{
			immediate: true,
			deep: true
		}
	)

	// 监听表单状态变化，更新本地配置
	// 使用防抖函数避免频繁触发
	const updateDebounceTimer = ref(null)
	watch(
		() => formState,
		() => {
			// 如果正在从 props 更新，则不触发更新
			if (isUpdatingFromProps.value) {
				return
			}

			// 清除之前的定时器
			if (updateDebounceTimer.value) {
				clearTimeout(updateDebounceTimer.value)
			}

			// 设置新的定时器，延迟执行更新
			updateDebounceTimer.value = setTimeout(() => {
				// 更新本地配置
				Object.assign(localConfig, {
					data: formState.data,
					dataSetConfig: formState.dataSetConfig
				})

				// 更新预览配置（这会立即反映在预览区域）
				emits('upDataConfig', cloneDeep(localConfig))
			}, 300) // 300ms的防抖时间
		},
		{
			deep: true
		}
	)

	// 监听props.config的变化，更新本地配置
	watch(
		() => props.config,
		(newConfig) => {
			if (newConfig && !isUpdatingFromProps.value) {
				// 设置标记位，表示正在从 props 更新
				isUpdatingFromProps.value = true

				// 更新本地配置
				Object.assign(localConfig, cloneDeep(newConfig))
				// 更新表单状态
				Object.assign(formState, {
					data: localConfig.data,
					dataSetConfig: localConfig.dataSetConfig
				})

				// 重置标记位
				setTimeout(() => {
					isUpdatingFromProps.value = false
				}, 0)
			}
		},
		{ deep: true }
	)
</script>
<style scoped>
	:deep(.ant-radio-button-wrapper) {
		padding: 0px;
		width: 100%;
	}
	:deep(.ant-radio-group) {
		display: flex;
		text-align: center;
	}
	:deep(.form-item) {
		margin-bottom: 0px;
	}
</style>
